package br.com.advance.automacao.services.impl;

import java.util.List;

import javax.persistence.NoResultException;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import br.com.advance.automacao.dao.ErroDao;
import br.com.advance.automacao.model.Erro;
import br.com.advance.automacao.services.ErroService;
import br.com.advance.automacao.services.exceptions.ValidationException;

@Service
@Transactional("transactionManager")
public class ErroServiceImpl implements ErroService {

	@SuppressWarnings("unused")
	private static final Logger logger = Logger.getLogger(ErroServiceImpl.class);

	@Autowired
	private ErroDao erroDao;

	@Override
	public Erro criar(Erro erro) throws ValidationException {
		validarDados(erro);
		return erroDao.create(erro);
	}

	@Override
	public Erro atualizar(Erro erro) throws ValidationException {
		validarDados(erro);
		return erroDao.update(erro);
	}

	private void validarDados(Erro erro) throws ValidationException {
		Erro erroEncontrado = erroDao.buscarPorCodigoCLP(erro.getCodigo(), erro.getClp().getId());
		if(erroEncontrado != null && (erro.getId() == null || !erroEncontrado.getId().equals(erro.getId()))) {
			throw new ValidationException("Código já cadastrado");
		}
	}

	@Override
	public Erro buscarErroPorCodigoClp(Long idCLP, String codigo) {
		try {
			return erroDao.buscarErroPorCodigoClp(idCLP, codigo);
		} catch(NoResultException e) {
			return null;
		}
	}

	@Override
	public List<Erro> buscarErroPorClp(Long idCLP) {
		try {
			return erroDao.buscarErroPorCodigoClp(idCLP);
		} catch(Exception e) {
			return null;
		}
	}

	@Override
	public Erro buscarPorId(Long id) {
		return erroDao.buscarPorId(id);
	}
}
